#!/bin/sh

##
## Packages
##
ROOT_PACKAGE=emc
PACKAGES="$ROOT_PACKAGE \
          $ROOT_PACKAGE/util"

##
##
##
build_emakefile () {
  src=$1; ebin=$2;
  (
  cd $src
  for f in *.erl ; do 
    if [ $f != "*.erl" ]; then 
      L=`echo $f|wc -c`
      /bin/echo -e "{'$src/\c";
      B=`echo $f|cut -c1-$(($L-5))`
      echo "$B', [{i, \"$ROOT/include\"}]}."
      /bin/echo -e ".\c" > /dev/tty
    fi
  done  
  ) > $2/Emakefile
}

##
##
##
build_emakefiles () {
  echo ; echo "# Building emakefiles..."
  build_emakefile "$ROOT/src" "$ROOT/ebin"
  for package in $PACKAGES; do 
    mkdir -p $ROOT/ebin/$package
    build_emakefile "$ROOT/src/$package" "$ROOT/ebin/$package"
  done
}

##
##
##
compile () {
  echo ; echo "# Compiling..." ;
  cp $ROOT/src/*.app $ROOT/ebin
  cd $ROOT/ebin
  $ERL -noshell -s make all -s erlang halt
  for package in $PACKAGES; do 
    cd $ROOT/ebin/$package
    $ERL -noshell -s make all -s erlang halt
  done
}

##
##
##
edoc() {
  echo ; echo "# Generating EDoc documentation..." ;
  OPTS="[{dir, \"$ROOT/priv/edoc\"}, {subpackages, true}, {source_path, [\"$ROOT/src\"]}]"
  eval $ERL -noshell -run edoc_run packages \'[$ROOT_PACKAGE]\' \'$OPTS\' -s init stop
}

##
##
##
clean () {
  echo ; echo "# Cleaning..." ;
  rm -f `find $ROOT/src | egrep "~$|beam$"`
  rm -rf $ROOT/ebin/*
  rm -f $ROOT/erl_crash.dump
}

##
##
##
mrproper () {
  clean
  find $ROOT/priv/edoc/* ! -name "overview.edoc" -exec rm -rf {} \; > /dev/null 2>&1
  rm -f $ROOT/src/emc.app
  rm -f $ROOT/src/build.sh
}

##
##
##
dir_resolve() {
  cd "$1" 2> /dev/null || return $?
  echo "`pwd -P`"
}

ROOT=$(dir_resolve `dirname $0`/..)
ERL=@ERL@

case "$1" in
 configure)
	build_emakefiles
        ;;

 compile)
	compile
        ;;

 edoc)
	edoc
        ;;

 clean)
	clean
        ;;

 mrproper)
	mrproper
        ;;

*)
	cat << @EOF@

 Usage: $0 {configure | compile | edoc | clean | mrproper | help}
 
		Buildit configure - rebuilds Emakefiles (list of Erlang files to compile)
		Buildit compile   - compiles all files listed in the Emakefiles
		Buildit edoc    - generates system documentation
		Buildit clean   - removes beam files
		Buildit mrproper- removes beam files
		Buildit help    - shows this help (so you already knew it!)

@EOF@

esac
